const int stby=2;
const int ain1=4;
const int ain2=3;
//one of 3,5,6,9,10,11
const int pwma=5;
//one of 3,5,6,9,10,11
const int pwmb=6;
const int bin1=7;
const int bin2=8;

void setup() {
  // put your setup code here, to run once:
  //bt.begin(115200);	// opens serial port, sets data rate
  pinMode(stby, OUTPUT);
  pinMode(ain1, OUTPUT);
  pinMode(ain2, OUTPUT);
  pinMode(pwma, OUTPUT);
  pinMode(13, OUTPUT);
  digitalWrite(stby, LOW);
  Serial.begin(115200);
  //prove the motor is indeed wired correctly on startup
  forward(255);
  //prove the bluetooth is wired correctly
  Serial.println("full speed");
  delay(1000);
  coast();
  Serial.println("coast");
}

void loop() {
}

const int foo=28;
const char f='f';
const char b='b';
const char s='s';

void serialEvent(){
  char buffer[4];
  /*
  //
   f1.
   f2.
   f3.
   f8.
   f9.
   s
   b1.
   b4.
   b8.
   b9.
   */
  Serial.readBytes(buffer,2);
  Serial.println(buffer);
  if(buffer[0]==f)
  {
    digitalWrite(13, HIGH);
    forward((buffer[1]-48)*foo);
  }
  else if(buffer[0]==b)
  {
    digitalWrite(13, HIGH);
    backward((buffer[1]-48)*foo);
  }
  else if(buffer[0]==s)
  {
    digitalWrite(13, HIGH);
    coast();
  }
  digitalWrite(13, LOW);
}

void forward(int speed)
{
  if(speed<=0)
  {
    //coast();
    speed=30;
  }
  //else
  {
    digitalWrite(ain1, HIGH);
    digitalWrite(ain2, LOW);
    digitalWrite(stby, HIGH);
    analogWrite(pwma, speed);
  }
}

void backward(int speed)
{
  if(speed<=0)
  {
    coast();
    speed=30;
  }
  //else
  {
    digitalWrite(ain1, LOW);
    digitalWrite(ain2, HIGH);
    digitalWrite(stby, HIGH);
    analogWrite(pwma, speed);
  }
}

void coast()
{
  digitalWrite(ain1, LOW);
  digitalWrite(ain2, LOW);
  digitalWrite(stby, LOW);
  analogWrite(pwma, 0);
}
